<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button
            style="float: right"
            @click="searchQueryList()"
            type="primary"
            size="small">
            查询结果
          </el-button>
        </div>
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
            <el-form-item label="输入搜索：">
              <el-input style="width: 203px" v-model="listQuery.username" placeholder="搜索用户名"></el-input>
            </el-form-item>
          </el-form>
        </div>
    </el-card>
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <!-- <el-button class="btn-add" @click="handleAddMember()" size="mini">
        添加新用户
      </el-button> -->
    </el-card>
    <el-table ref="productTable"
                :data="list"
                style="width: 100%"
                v-loading="listLoading"
                border>
        <el-table-column label="编号"  width="60" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="昵称" width="120" align="center">
          <template slot-scope="scope"> {{scope.row.nickname}} </template>
        </el-table-column>
        <el-table-column label="用户名" width="120" align="center">
          <template slot-scope="scope">{{scope.row.username}}</template>
        </el-table-column>
        <el-table-column label="用户编号" width="120" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.singeStatus == 'notedit'">
                <p>{{scope.row.code}}</p>
                <el-button @click="editSingleCode(scope.$index, scope.row)" type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            </div>
            <div v-else>
                <el-input v-model="scope.row.code" placeholder="请输入内容"></el-input>
                <el-button @click="saveSingleCode(scope.$index, scope.row)" type="primary" icon="el-icon-s-claim" size="mini">保存</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template slot-scope="scope">{{scope.row.gender ==1?'男':'女'}}</template>
        </el-table-column>
        <el-table-column label="手机号" width="120" align="center">
          <template slot-scope="scope">{{scope.row.phone||'无'}}</template>
        </el-table-column>
        <el-table-column label="消费金额" width="140" align="center">
          <template slot-scope="scope">
            <el-button size="mini" slot="reference" type="primary" @click="checkMemberOrder(scope.row.id,scope.$index)">查询详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="会员积分" width="100" align="center">
           <template slot-scope="scope">{{scope.row.integration ||0}}</template>
        </el-table-column>
        <!-- <el-table-column label="级别" width="100" align="center">
          <template slot-scope="scope">{{scope.row.growth}}</template>
        </el-table-column> -->
       
        <!-- <el-table-column label="城市" width="100" align="center">
          <template slot-scope="scope">{{scope.row.city }}</template>
        </el-table-column> -->
         <el-table-column label="注册时间" width="230" align="center">
          <template slot-scope="scope">{{scope.row.createTime}}</template>
        </el-table-column>
        <!-- <el-table-column label="邮箱" width="200" align="center">
          <template slot-scope="scope">{{scope.row.email}}</template>
        </el-table-column> -->
        <!-- <el-table-column label="备注" width="200" align="center">
          <template slot-scope="scope">{{scope.row.note}}</template>
        </el-table-column> -->
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                @click="handleEditMember(scope.$index, scope.row)">编辑
              </el-button> -->
              <el-button
                size="mini"
                @click="handleUpdateRole(scope.$index, scope.row)" :disabled="scope.row.isAgent == 1">转移到经销商
              </el-button>
              <!-- <el-button
                size="mini"
                type="danger"
                @click="handleDeleteMember(scope.$index, scope.row)">删除
              </el-button> -->
          </template>
        </el-table-column>
    </el-table>
    <!-- 新增用户的弹窗 -->
    <el-dialog title="新增用户" :visible.sync="isNewMemberOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="newForm" style="width:25rem;" :rules="newFormRules" >
            <el-form-item label="登录账号" prop="Membername" required label-width="5rem">
                <el-input v-model="newForm.Membername" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="5rem">
                <el-input v-model="newForm.password" type="password" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
             <el-form-item label="昵称" prop="nickName" required label-width="5rem">
                <el-input v-model="newForm.nickName" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" label-width="5rem">
                <el-input v-model="newForm.email" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="备注"  label-width="5rem">
                <el-input v-model="newForm.note" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewMember('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewMemberOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑用户的弹窗 -->
    <el-dialog title="编辑用户" :visible.sync="isEditMemberOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:25rem;" :rules="editFormRules" >
            <el-form-item label="账号" prop="Membername" required label-width="5rem">
                <el-input v-model="editForm.Membername" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="nickName" required label-width="5rem">
                <el-input v-model="editForm.nickName" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="5rem">
                <el-input v-model="editForm.password" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="note" label-width="5rem">
                <el-input v-model="editForm.note" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveMemberInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditMemberOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 转移到经销商的弹窗 -->
    <el-dialog title="转移到经销商" :visible.sync="isTransferMemberOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <!-- <div :model="editRoleForm" style="width:25rem;" :rules="editRoleFormRules" > -->
        <div style="width:25rem;" >
          <!-- <el-checkbox-group v-model="selectedRole" @change="roleChange">
            <el-checkbox v-for="role in allRoleList" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
          </el-checkbox-group> -->
          <p>此操作不可逆，确定要继续吗？</p>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="transferMember" style="color:#fff;background-color:#417FF6;">确定</el-button>
            <el-button @click="isTransferMemberOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 某个会员的消费详情弹窗 -->
    <el-dialog title="消费金额详情" :visible.sync="isMmeberOrderOpen" :close-on-click-modal="true" :show-close="true" class="adjustmentBox">
      <div v-if="memberOrderDetail">
      <p><span>消费总金额:</span><span>{{moneyIcon}} {{memberOrderDetail.consumeAmount}}</span></p>
      <p><span>订单数量:</span><span>{{memberOrderDetail.orderCount}}</span></p>
      </div>
      <div v-else>暂无数据</div>
      <!-- <el-table :data="memberOrderDetail">
        <el-table-column width="150" label="消费总金额">
          <template slot-scope="scope">{{scope.row.consumeAmount}}</template>
        </el-table-column>
        <el-table-column width="100" label="订单数量">
          <template slot-scope="scope">{{scope.row.orderCount}}</template>
        </el-table-column>
      </el-table> -->
    </el-dialog>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[30,40,60]"
        :current-page.sync="listQuery.pageNum"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
    import {
    fetchMemberList,
    transferMember,
    getMemberOrderSum,
  } from '@/api/member'
   import {fetchRoleList} from '@/api/role'

  const defaultListQuery = {
    username:'',
    keyword: null,
    pageNum: 1,
    pageSize: 30,
  };
  export default {
    name: "MemberList",
    data() {
      return {
        moneyIcon:process.env.MONEY_ICON,
        isMmeberOrderOpen:false,//某个会员的消费详情弹窗
        memberOrderDetail:[],//某个会员的消费详情
          list:[],
          listQuery:Object.assign({}, defaultListQuery),
          total:0,//页面上显示的一共有多少条数据
          newForm:{//新增用户弹框里内容
            Membername:'',
            nickName:'',
            password:'',
            note:'',
            email:'',
            //icon:"",//用户头像
          },
          editForm: {//编辑用户弹框里内容
            currentUId:0,
            Membername:'',
            nickName:'',
            password:'',
            note:'',
          },
          newFormRules:{
            Membername:[
                { required: true,  message: '账号不能为空', trigger: ['blur','change']}
             ],
             nickName:[
                { required: true,  message: '用户名不能为空', trigger: ['blur','change']}
             ],
             password:[
                { required: true,  message: '密码不能为空', trigger: ['blur','change']},
                {min:6, max:20, message:"密码长度不能少于6且不能大于20", trigger:['blur','change']}
             ],
             
          },
          editFormRules:{
            Membername:[
                { required: true,  message: '账号不能为空', trigger: ['blur','change']}
             ],
             nickName:[
                { required: true,  message: '用户名不能为空', trigger: ['blur','change']}
             ],
          },
          currentOpeId:0,//编辑角色的当前用户id
          currentOpeNickname:'',//编辑角色的当前用户nickname
          allRoleList:[],//所有的角色列表
          MemberRoleId:[],//当前用户的role id
          selectedRole:[],//用户弹窗里选择的选择的role id
          isNewMemberOpen:false,//新增用户弹窗
          isEditMemberOpen:false,//编辑用户弹窗
          isRoleOpen:false,//编辑角色弹窗
          isTransferMemberOpen:false,//转移到经销商
          currentOpenCode:'',//用户编号
      }
    },
    created() {
      this.getList();
      this.getRoleList();
    },
    methods:{
      getList() {
        this.listLoading = true;
        fetchMemberList(this.listQuery).then(response => {
            this.listLoading = false;
            let list = response.data.list;
            list.map((item)=>{
              item.singeStatus = 'notedit'
            })
            this.list =list;
            this.total = response.data.total;
        });
      },
      editSingleCode(index,row){
        let idx = index;
        let self= this;
        self.list[idx].singeStatus = 'edit'
      },
      saveSingleCode(index,row){
        let self = this;
        let id = row.id;
        let name = row.nickname;;
        let code = row.code;
        if(!code){
          self.$message({
             message: '请输入code值',
              type: 'warning',
              duration: 2000
          })
          return
        }
        let params = {};
        params.memberId = id;
        params.nickname = name;
        params.code = code;
        // params.append('memberId', id);
        // params.append('nickname', name);
        // params.append('code', code);
        transferMember(params).then(res =>{
           if(res.code === 200){
            self.$message({
              message: '更新成功！',
              type: 'success',
              duration: 2000
            });
            self.getList();
           }
        })
      },
      searchQueryList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      checkMemberOrder(id,index){
        getMemberOrderSum(id).then(res=>{
          if(res.code ==200){
            this.memberOrderDetail = res.data;
            this.isMmeberOrderOpen = true;
          }
        })
      },
      handleEditMember(index,item){
        this.isEditMemberOpen = true;
        this.editForm.currentUId = item.id;
        this.editForm.Membername = item.Membername;
        this.editForm.nickName = item.nickName;
        this.editForm.note = item.note;
      },

      handleAddMember(){
          this.isNewMemberOpen = true;
      },
      
      saveNewMember(){
          console.log(this.newForm);
        newMemberInfo(this.newForm).then(response=>{
            if(response.code == 200){
                this.$message({
                  message: '新建成功',
                  type: 'success',
                  duration: 1000
              });
            this.isNewMemberOpen=false;
            this.getList();
            }
        })
      },
      saveMemberInfo(){
          //console.log(this.editForm);
          let passTemp= this.editForm.password;
          if (!passTemp){
            delete this.editForm.password
          }
          //console.log(this.editForm);
        updateMemberInfo(this.editForm.currentUId,this.editForm).then(response=>{
            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1000
            });
            this.isEditMemberOpen=false;
            this.getList();
        });
      },
      handleUpdateRole(index,item){
        console.log(item.id);
        this.currentOpeId = item.id;
        this.currentOpenCode = item.code;
        this.currentOpeNickname = item.nickname;
        this.isTransferMemberOpen = true;
       // this.getCurMemberRole();
      },
      transferMember(){
        let self = this;
        let id = self.currentOpeId;
        let name = self.currentOpeNickname;
        let params = {};
        params.memberId =id;
        params.nickname =name;
        params.settingToDistributor = true;
        // params.append('memberId', id);
        // params.append('nickname', name);
        // params.append('code', self.currentOpenCode);
        // params.append('settingToDistributor', true);
        transferMember(params).then(res =>{
           if(res.code === 200){
            self.isTransferMemberOpen = false;
            self.$message({
              message: '已转为经销商',
              type: 'success',
              duration: 1000
            });
            self.getList();
           }
        })
        

      },
      getRoleList() {
        let self = this;
        fetchRoleList().then(response => {
            if(response.code === 200){
              self.allRoleList = response.data;
            }
        });
      },
      getCurMemberRole(){
        let self = this;
        let id = self.currentOpeId;
        getCurMemberRole(id).then(res =>{
          let roleInfo = res.data;
          let roleIds =[];
          roleInfo.forEach(item=>{
            roleIds.push(item.id);
          })
          self.MemberRoleId = roleIds; //当前用户的role id
          self.selectedRole = JSON.parse(JSON.stringify(roleIds));
          self.isRoleOpen =true;
        })
      },
      roleChange(){
        console.log(this.selectedRole)
      },
      saveMemberRoleInfo(){
        let self = this;
        if (!self.selectedRole || self.selectedRole.length ==0){
          this.$message({
            message: '请选择合适的角色',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        let params = new URLSearchParams();
        params.append('adminId', self.currentOpeId);
        params.append('roleIds', self.selectedRole);
        updateMemberRoleInfo(params).then(res=>{
          if(res.code === 200){
            this.$message({
              message: '角色修改成功',
              type: 'success',
              duration: 1000
            });
            self.isRoleOpen = false;
            self.getList();
          }
        })
      },
      handleDeleteMember(index,item){
          let self = this;
           self.$confirm('删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                console.log(11);
                deleteMember(item.id).then(response=>{
                    console.log(22)
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
.btn-add{
    font-size: 14px;
    padding: 10px;
    margin-top: -8px;
  color:#fff;
  background-color:#417FF6;
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 
</style>